package com.tao.xitong.security;


import com.tao.xitong.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
//后面被扔到SecurityConfug里面用到
//作用：通过用户名解析token，查出用户信息把用户信息放入SecurityContextHolder
// 将该过滤器组件注入Spring容器
@Component
// 继承OncePerRequestFilter，确保每个请求只过滤一次
public class JwtRequestFilter extends OncePerRequestFilter {

    // 用户详情服务，用于加载用户信息
    private UserDetailsService userDetailsService;

    // Jwt工具类，用于Jwt令牌的生成和验证
    private JwtUtil jwtUtil;

    /**
     * 构造函数，注入用户详情服务和Jwt工具类
     */
    public JwtRequestFilter(UserDetailsService userDetailsService, JwtUtil jwtUtil) {
        this.userDetailsService = userDetailsService;
        this.jwtUtil = jwtUtil;
    }

    /**
     * 执行过滤操作
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        // 如果请求路径以"/api/auth"开头，直接传递请求，不进行Jwt验证
        if (request.getServletPath().startsWith("/api/auth")) {
            chain.doFilter(request, response);
            return;
        }

        // 获取请求头中的Authorization信息
        final String authorizationHeader = request.getHeader("Authorization");

        // 初始化用户名和Jwt为空
        String username = null;
        String jwt = null;

        // 如果Authorization头存在且以"Bearer "开头，提取Jwt并解析出用户名
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
        }

        // 如果用户名存在且当前没有进行身份验证
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            // 通过用户详情服务加载用户信息
            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);

            // 验证Jwt是否有效
            if (jwtUtil.validateToken(jwt, userDetails.getUsername())) {
                // 创建身份验证令牌
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                // 设置额外的详细信息
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 将身份验证令牌设置到Security上下文中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        // 继续传递请求
        chain.doFilter(request, response);
    }
}

